import {
	TokenKey
} from "../vars/StoreKeys.js"
import Config from "../vars/Config.js"
const Http = function(url, method, data = {}, header = {}, config = {}) {
	return new Promise((resolve, reject) => {
		const baseUrl = Config.baseUrl;
		if (url.startsWith('/')) {
			url = `${baseUrl}${url}`
		} else {
			url = `${baseUrl}/${url}`
		}
		try {
			const token = uni.getStorageSync(TokenKey)
			if (token && token.length > 0) {
				header.Authorization = 'Bearer ' + token
			}
		} catch (e) {

		}
		console.log('http url:', url)
		console.log('http params:', data)
		uni.request({
			url,
			method,
			data,
			header,
			...config,
			success(res) {
				console.log(`statusCode【${res.statusCode}】 http success:`, res.data)
				if (res.statusCode !== 200) {
					if (!res.data || !res.data.state) {
						return reject(new Error(res.errMsg))
					}
				}
				const data = res.data || {}
				if (data.state !== 200) {
					if (data.state === 401) {
						return reject(new Error("权限不足"))
					}
					return reject(new Error(data.message || ''))
				}
				const results = data.data || {};
				if (!results.message && !Array.isArray(results)) {
					results.message = data.message
				}
				resolve(results)
			},
			fail(err) {
				console.log('http error:', err)
				reject(err)
			}
		})
	})
}
Http.get = (url, data = {}, header = {}, config = {}) => Http(url, 'get', data, header, config);
Http.put = (url, data = {}, header = {}, config = {}) => Http(url, 'put', data, header, config);
Http.post = (url, data = {}, header = {}, config = {}) => Http(url, 'post', data, header, config);
Http.head = (url, data = {}, header = {}, config = {}) => Http(url, 'head', data, header, config);
Http.patch = (url, data = {}, header = {}, config = {}) => Http(url, 'patch', data, header, config);
Http.delete = (url, data = {}, header = {}, config = {}) => Http(url, 'delete', data, header, config);
Http.options = (url, data = {}, header = {}, config = {}) => Http(url, 'options', data, header, config);

export default Http;
